
	$(document).bind('mlhAPI_loaded',function(){
		var showData = function(data){
			if(data['result'] == 'success'){
				var p = 1;
				if(data.data.element.model=='news'){
					breadcrumbList[1] = ['Новости','/news','news'];
					p++;
				}
				breadcrumbList[p] = [data.data.element.title,'/article/'+data.data.element.article_id,'article'];
				breadcrumbList[p+1] = false;
				buildBreadcrumb();
				$('#general_content>article>h1:first').text(data.data.element.title);
				$('#general_content>article>p:first').text(data.data.element.description);
                mlhAPI.article.getComments(
				{
					id: data.data.element.article_id,
					callback: showComments
				});
			}
		}
		var showNews = function(data){
			if(data['result'] == 'success'){
				breadcrumbList[1] = ['Новости','/news','news'];
				breadcrumbList[2] = false;
				buildBreadcrumb();
				$('#general_content>article>h1:first').text('Новости');
				$('#general_content>article>p:first').html('');
				$(data.data).each(function(){
					$('#general_content>article>p:first').append($('<p><a href="/article/' + this.article_id + '" rel="article" class="ajax">' + this.title + '</a></p>'));
				});
			}
		}
        var parsetree = function(el,tree){
            var li = $('<li class="comment" rel="'+tree.comment_id+'"/>');
            li.append(
                $('<p/>').append($('<a href="/user/'+tree.user_id+'">'+tree.user_name+"</a>"))
                    .append($("<span>"+tree.description+"</span>"))
                    .append($("<i class='icon-trash'></i>"))
                ).find('i').click(function(){
                    delComment(tree.comment_id);
                });
            li.append($("<span class='req' onclick='$(this).hide();$(this).next().show()'>Написать ответ</span>"));
            li.append($("<div style='display:none'>").append($('<textarea>')).append($('<br>')).append($("<input type='button' value='Ответить' >").click(function(){
                addComment(tree.comment_id,
                {
                    comment_id:6345,
                    user_id:1,
                    user_name:2,
                    description:$(this).parent().find('textarea').attr('value')
                });
                
                $(this).parent().hide();
                $(this).parent().prev().show();
            })));
            if(tree.child){
                var subtree = $('<ul class="unstyled" style="margin-left:20px;"/>');
                for(var i =0; i<tree.child.length; i++){
                    parsetree(subtree,tree.child[i]);
                }
                li.append(subtree);
            }
            el.append(li);
        }
        var deleteFromTree = function(id){
            var li = $('.comment[rel='+id+']');
            if(!li.length) return;
            var ul = li.find('ul:first li');
            if(ul.length > 0){
                li.find('p:first i, span.req:first, div:first').remove();
                li.find('span:first ').remove();
                li.find('p:first > span').text('Удалено');
            }else li.remove();

        }
        var showComments = function(data){
            var ul = $('<ul class="unstyled comments"/>');
            for(var i =0; i<data.data.length; i++){
                parsetree(ul,data.data[i]);
            }
            $('#general_content>article>p:first').append('<hr/>').append(ul);
        }
        var delComment = function(id){
            mlhAPI.article.delComment({
                id: id,
                callback: function(result){
                    if(result['result'] == 'success'){
                        if(result.data['error'])alert(result.data['error']);
                        else deleteFromTree(id);
                    }
                }
            });
        }
        var addComment = function(id,data){
            if(id){
                var li = $('.comment[rel='+id+']');
                if(!li.length) return;
                var ul = li.find('ul:first');
                if(!ul.length) {
                    ul = $('<ul class="unstyled" style="margin-left:20px;"/>');
                    li.append(ul);
                }
            } else {
                ul = $('.comments');
            }
            mlhAPI.article.setComment({
                parent_id: id,
                model_id: 1,///костыль
                description: data.description,
                callback: function(result){
                    if(result['result'] == 'success'){
                        if(result.data['error'])alert(result.data['error']);
                        else parsetree(ul,data);
                    }
                }
            });
        }
		var breadcrumbList = [['Главная','/article/1','article'],false,false];
		var buildBreadcrumb = function(){
			var el = $('ul.breadcrumb:first');
			if(breadcrumbList.length<2){
				el.hide();
			}
			el.html('');
			var buildEl = function(data,last){
				if(!data) return;
				var el = $('<li>');
				el.append($('<a href="'+data[1]+'" class="ajax" rel="'+data[2]+'"></a>').text(data[0]));
				if(!last)el.attr('class','active');
				else el.append($('<span class="divider">/</span>'));
				return el;
			}
			el.append(buildEl(breadcrumbList[0],breadcrumbList[1]))
			el.append(buildEl(breadcrumbList[1],breadcrumbList[2]))
			el.append(buildEl(breadcrumbList[2],breadcrumbList[3])).show();
		}
		$('.navbar a.ajax').click(function(){
			var el = $(this);
			var url = el.attr('href').split("/");
			if(!url[0])url.shift();
			location.hash = el.attr('href');
			switch(url[0]){
				case "article": mlhAPI.article.get(
				{
					id: url[1],
					callback: showData
				});
				break;
				case "news": mlhAPI.article.getNews(
				{
					callback: showNews
				});
				break;
			}
		});
		var ajaxObserver = {
			article: function(url,el){
				mlhAPI.article.get(
				{
					id: url[1],
					callback: showData
				});
			},
			news: function(url,el){
				mlhAPI.article.getNews(
				{
					callback: showNews
				});
			}
		}
		$('#general_content a.ajax, ul.breadcrumb:first a.ajax').live('click',function(){
			var el = $(this);
			var url = el.attr('href').split("/");
			var rel = el.attr('rel');
			if(!url[0])url.shift();
			location.hash = el.attr('href');
			ajaxObserver[rel](url,el);
		});
    });
	$('.help').css({display: 'block'}).tooltip(
	{
		placement: 'bottom'
	});
!function ($) {

  $(function(){
	// fix sub nav on scroll
    var $win = $(window)
      , $nav = $('.subnav')
      , navTop = $('.subnav').length && $('.subnav').offset().top - 0
      , isFixed = 0

    processScroll()

    $win.on('scroll', processScroll)

    function processScroll() {
      var i, scrollTop = $win.scrollTop()
      if (scrollTop >= navTop && !isFixed) {
        isFixed = 1
        $nav.addClass('subnav-fixed')
      } else if (scrollTop <= navTop && isFixed) {
        isFixed = 0
        $nav.removeClass('subnav-fixed')
      }
    }
    $('.ajax').live('click',function(){
    	var el = $(this);
    	if(el.attr('rel')){
	    	$('.navbar .container li').removeClass('active');
	    	$('.navbar .container li[rel=' + el.attr('rel') + ']').addClass('active');
	    	if(!el.parent().hasClass('active'))el.parent().addClass('active');
    	}
        return false;
    })
})

}(window.jQuery)
